package com.wang.tasker.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ConfigElement {
	
	private Element element;
	
	public ConfigElement(Element element){
		this.element = element;
	}
	
	public ConfigElement(File confFile) throws DocumentException{
		SAXReader reader = new SAXReader();
		Document configDom = reader.read(confFile);
		this.element = configDom.getRootElement();
	}

	public ConfigElement selectSingleElement(String xpath) {
		Element ele = (Element)element.selectSingleNode(xpath);
		if(ele == null) return null;
		return new ConfigElement(ele);
	}
	
	public String getText(){
		return element.getText();
	}

	public String getTextTrim() {
		return element.getTextTrim();
	}

	public String attributeValue(String name) {
		return element.attributeValue(name);
	}

	public ElementList selectElements(String xpath) {
		List eleList = element.selectNodes(xpath);
		ElementList answer = new ElementList(new ArrayList());
		for(Object eleObj:eleList){
			if(!(eleObj instanceof Element))
				continue;
			Element ele = (Element)eleObj;
			answer.add(new ConfigElement(ele));
		}
		return answer;
	}
	
	public Element getElement(){
		return element;
	}
	
	public String getName(){
		return element.getName();
	}
	
	public List elements(){
		List list = element.elements();
		List answer = new ArrayList();
		for(Object eleObj:list){
			if(!(eleObj instanceof Element))
				continue;
			Element ele = (Element)eleObj;
			answer.add(new ConfigElement(ele));
		}
		return answer;
	}
	
}
